<?php

namespace app\common\service;
use app\common\service\AbstractService;
use app\common\service\CommonSystemImportService;
use app\data\util\Rabbitmq;
use app\systems\logic\MqTaskPushLogic;
use app\systems\model\CommonSystemImportModel;
use app\systems\model\SystemMqGroupModel;
use app\systems\model\CommonSystemImportDetailModel;
use think\facade\Cache;

class CommonSystemImportInfoDetailService extends AbstractService
{

    public $system_import_model;
    public $system_import_detail_model;
    const STATUS_DETAIL_INIT = 0;
    const STATUS_DETAIL_SUCCESS = 1;
    const STATUS_DETAIL_FAIL = 2;
    const STATUS_DETAIL_CANCEL= 3;
    const STATUS_MAP = [
        self::STATUS_DETAIL_INIT => '初始化',
        self::STATUS_DETAIL_SUCCESS => '成功',
        self::STATUS_DETAIL_FAIL => '失败',
        self::STATUS_DETAIL_CANCEL => '取消',
    ];



    #导入对应操作方法,共有的可写在当前service中，各平台特殊的写在各平台service中
    const WITCH_FUNCTION = [
        CommonSystemImportService::TYPE_IMPORT_INCOMPLETE_SKU  => 'import_incomplete_sku',
        CommonSystemImportService::TYPE_IMPORT_INCOMPLETE_TIME => 'import_incomplete_time',
        CommonSystemImportService::TYPE_IMPORT_SF_PAGE         => 'import_sf_page',
        CommonSystemImportService::TYPE_IMPORT_QC_PAGE         => 'import_qc_page',
        CommonSystemImportService::TYPE_IMPORT_LIAN_LIAN       => 'import_lian_lian',
        CommonSystemImportService::TYPE_IMPORT_MONTH_OLD       => 'import_month_old',
        CommonSystemImportService::TYPE_IMPORT_MONTH_NEW       => 'import_month_new',
    ];





    /**
     * @Notes:处理导入的任务
     * @Author: TCP
     * @Date: 2021/3/24
     * @Time: 16:19
     */
    public function run_import_detail($id){

        try {
            //操作对应的数据
            $this->system_import_detail_model = new CommonSystemImportDetailModel();
            $model = $this->system_import_detail_model->find($id);
            $model = objectToArray($model);
            if(empty($model)){
                return true;
            }
            if($model['status']!=0){
                return true;
            }
            $this->system_import_model = new CommonSystemImportModel();
            $import_model = $this->system_import_model->find($model['import_id']);
            $import_model = objectToArray($import_model);
            if(empty($import_model)){
                return true;
            }

            $method = $this::WITCH_FUNCTION[$import_model['import_type']];
            if (!method_exists($this, $method)) {
                return true;
            }
            $this->$method($id);
        } catch (\Exception $e) {
            return $e->getMessage();
        }
        return true;
    }


    /**
     * @Notes:更改任务状态
     * @Author: TCP
     * @Date: 2021/3/25
     * @Time: 13:50
     * @param $task_id
     * @return bool
     */
    public function parentStatusChange($import_id)
    {
        return true;
    }



    /**
     * 操作子数据
     * @param $data             //入库写表数据
     * @param $platform_code
     * @param $services         //类路径
     * @param $is_sub_library   //是否分库
     * @param $importType   //导入类型
     * @return bool
     * @author: xx
     * @Date: 2024/3/21
     */
    public function operate_detail_data($data,$platform_code,$services,$is_sub_library,$importType=''){
        try {
            $rabbitmq = app(rabbitmq::class, ['default']);
            foreach($data as $k=>$v){
                $class_path = get_class($services);
                $params = [
                    'platform_code' =>TIKTOK,
                    'class_path'    =>$class_path,
                    'is_sub_library'=>$is_sub_library,
                    'import_type'   =>$importType,
                    'data'          =>$v
                ];
                $rabbitmq->mq_send_message($params,[
                    'queue_name'   => 'sale_center_system_import_task_detail',
                    'exchange_name'=> 'sale_center_system_import_exchange',
                    'bind_key'     => 'sale_center_system_import_detail'
                ]);
            }
            Cache::store('redis')->set('insert_detail_no_'.$data[0]['import_id'],6,3600*3);
            return true;
        }catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 导入具体入库执行队列
     * @param array $params
     * @author: xx
     * @Date: 2024/3/21
     */
    public function system_import_task_detail($params = [])
    {

        $platform_code = $params['platform_code'];
        $service = $params['class_path'];
        $is_sub_library = $params['is_sub_library'];
        $data = $params['data'];
        $model = new CommonSystemImportDetailModel();
        $res = $model->save($data);
        if($res){
            $pushmessage['type'] = MqTaskPushLogic::TYPE_COMMON_SYSTEM_IMPORT;
            $pushmessage['id']   = $model->id;
            $pushmessage['platform_code'] = $platform_code;
            $pushmessage['is_sub_library'] = $is_sub_library;
            $pushmessage['import_type'] = isset($params['import_type']) && $params['import_type']?$params['import_type']:'';
            if (getValue($params,'queue_name','')){
                $pushmessage['queue_name']=$params['queue_name'];
            }
            //推到队列
            MqTaskPushLogic::common_system_import_task_push($pushmessage);
        }
        return true;
    }


    /**
     * 导入状态修改
     * @param $import_id
     * @return bool|\end\libraries\abstract_broker\unknown|mixed|null
     * @author: xx
     * @Date: 2024/3/21
     */
    public function parentStatusChangeNew($import_id)
    {
        try {
            $model = (new CommonSystemImportModel())->find(["id"=>$import_id]);
            if (empty($model)) {
                throw new \Exception('导入任务不存在');
            }
            $model= objectToArray($model);

            $detail_model = new CommonSystemImportDetailModel();
            # 成功和失败需要前置条件，成功和失败记录数执行完成数和总数一致;除了成功、失败，其他全部赋值处理中状态

            $detail_num = $detail_model->where('import_id',$import_id)
                ->whereIn('status',[self::STATUS_DETAIL_SUCCESS,self::STATUS_DETAIL_FAIL])
                ->field(['count(*) num'])
                ->find();
            $detail_num = objectToArray($detail_num);
            $model['upload_num'] = 1;
            if($detail_num['num'] == $model['upload_num']){

                # 只要有一条失败就给失败状态
                if ($detail_model->where(['status'=>self::STATUS_DETAIL_FAIL,'import_id'=>$import_id])->field('id')->find()) {
                    $model['import_status'] = CommonSystemImportService::STATUS_FAIL;
                }else{
                    $model['import_status'] = CommonSystemImportService::STATUS_SUCCESS;
                }
            }else{
                # 处理中
                $model['import_status']= CommonSystemImportService::STATUS_PENDING;
                #导入超过3天的标记失败@2022-09-06
                if($model['created_unix'] && (time() - $model->created_unix >= 86400 * 3)){
                    $model['import_status'] = CommonSystemImportService::STATUS_FAIL;
                }
            }
            (new CommonSystemImportModel())->where(["id"=>$import_id])->update(['import_status'=>$model['import_status']]);
            return json(DefaultResponse(200, true,'操作成功', null));
        } catch (\Exception $e) {
            return json(DefaultResponse(201, false, $e->getMessage(), null));
        }
        return json(DefaultResponse(200, true,'操作成功', null));
    }


}